package me.luraframework.gateway.module.route;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import me.luraframework.commons.utils.JsonUtils;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ description: RedisRouteDefinitionRepository
 * @ author: Liu Ran
 * @ data: 7/11/23 19:12
 */
@Repository
@RequiredArgsConstructor
public class MysqlRouteDefinitionRepository implements RouteDefinitionLocator {
    private final GwApiRepository gwApiRepository;
    private final ApplicationContext applicationContext;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        return gwApiRepository.findAll()
                .map(gwApi -> {
                    RouteDefinition routeDefinition = new RouteDefinition();
                    routeDefinition.setId(gwApi.getName());
                    routeDefinition.setUri(URI.create(gwApi.getUri()));

                    PredicateDefinition predicate = new PredicateDefinition("Path=" + gwApi.getPath());
                    routeDefinition.setPredicates(ImmutableList.of(predicate));
                    // 增加Filter
                    FilterDefinition filterDefinition = new FilterDefinition("StripPrefix=1");
                    routeDefinition.setFilters(ImmutableList.of(filterDefinition));
                    // 装载附加信息
                    Map<String, Object> metadata = routeDefinition.getMetadata();
                    metadata.put(GwApi.ROUTE_METADATA_AUTH_TYPE, gwApi.getAuthType());
                    metadata.put(GwApi.ROUTE_METADATA_SWAGGER_URL, gwApi.getSwaggerUrl());

                    return routeDefinition;
                });
    }

}
